import axios from 'axios'
import qs from 'qs' // json转为urlencode格式
import Vue from 'vue'
import { Toast } from 'vant'
import router from '../router'
import { getToken } from '_utils/token.js'
const vm = new Vue()
// 添加配置
const request = axios.create({
  baseURL: '/conner'
})

//
const uplodRequest = axios.create({
  baseURL: '/conner',
  header: { 'Content-Type': 'multipart/form-data' }
})
Vue.prototype.uploadRe = uplodRequest
// 添加拦截器
request.interceptors.request.use(function (config) {
  console.log(config)
  if (config.method === 'post' && config.data) {
    config.data = qs.stringify(config.data)
  }
  // if (config.url === 'dfs/upload/file') {
  //   // config.data = qs.stringify(config.data)
  //   config.headers['Content-Type'] = 'multipart/form-data'
  // }
  // 请求头中添加token
  if (getToken()) {
    config.headers.token = getToken()
  }
  vm.$showLoading()
  return config
}, function (error) {
  vm.$hideLoading()
  return Promise.reject(error)
})

request.interceptors.response.use(function (response) {
/*
  const errcode = [401, 403]
  if (errcode.includes(res.data.code)) {
    Toast({
      type: 'fail',
      message: 'token错误或者过期',
      onClose: () => {
        router.push('/login')
      }
    })
  }
  */
  if (response.data.code === 2000) {
    Toast({
      type: 'fail',
      message: response.data.msg,
      onClose: () => {
        localStorage.removeItem('token')
        router.push('/login')
      }
    })
  }
  // if (response.data.code === 0) {
  //   return response.data.data
  // }
  vm.$hideLoading()
  return response
}, function (error) {
  vm.$hideLoading()
  return Promise.reject(error)
})
export default request
